package net.wanho.shop.advice;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import net.wanho.shop.dto.LoginUserDTO;
import net.wanho.shop.po.LoginLog;
import net.wanho.shop.service.LoginLogService;
import net.wanho.shop.util.AddressUtil;
import net.wanho.shop.util.ServletUtil;
import net.wanho.shop.vo.AjaxResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 登录日志切面
 */
@Component
@Aspect
public class LoginLogAspect {

    @Resource
    private LoginLogService loginLogService;

    @Pointcut("execution( * net.wanho.shop.controller.LoginController.login(..))" +
            "|| execution( * net.wanho.shop.controller.LoginController.captchaLogin(..))")
    public void pc() {
    }

    @Around("pc()")
    public Object around(ProceedingJoinPoint joinPoint) {

        HttpServletRequest request = ServletUtil.getRequest();

        LoginLog loginLog = new LoginLog();
        LoginUserDTO loginUserDTO = (LoginUserDTO) joinPoint.getArgs()[0];
        loginLog.setUserName(loginUserDTO.getUsername());
        loginLog.setIpaddr(AddressUtil.getIpAddr(request));
        loginLog.setLoginLocation(AddressUtil.getLocationByIp(loginLog.getIpaddr()));
        //
        String UserAgent = request.getHeader("User-Agent");
        UserAgent agent = UserAgentUtil.parse(UserAgent);
        loginLog.setBrowser(agent.getBrowser().getName());
        loginLog.setOs(agent.getOs().getName());
        loginLog.setLoginTime(LocalDateTime.now());

        try {
            Object proceed = joinPoint.proceed();
            AjaxResult result = (AjaxResult) proceed;
            loginLog.setStatus("0");
            loginLog.setMsg("登陆成功");

            return result;
        } catch (Throwable e) {
            loginLog.setStatus("1");
            loginLog.setMsg(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            loginLogService.add(loginLog);
        }

    }

}